import React, { FC,useEffect, useState,useImperativeHandle,forwardRef  } from 'react';
import { Avatar, Button, List, Skeleton } from 'antd';
import { getDocumentListByDir,downloadFileById } from '../../../apis/backhub/directory';

interface DataType {
	id?:number;
	fileName?: string;
	filePath?: string;
	uploadDateTime?: string;
	loading: boolean;
}

const PAGE_SIZE = 10;

const DirectoryDocumentList= (props:{directoryId:number}, ref) => {
  const [initLoading, setInitLoading] = useState(true);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<DataType[]>([]);
  const [list, setList] = useState<DataType[]>([]);
  const [page, setPage] = useState(1);
  useImperativeHandle(ref,() => ({ 
	  func 
	})
  );

  const func=()=>{
	setPage(1);
	setData([])
	setList([])
	fetchData(page).then((res) => {
	  const results = Array.isArray(res) ? res : [];
	  setInitLoading(false);
	  setData(results);
	  setList(results);
	});
  }

  const fetchData = async(currentPage: number) => {
	const params = {
		directoryId:props.directoryId,
		pageNo:currentPage,
		pageSize:PAGE_SIZE
	} 
    const res = await getDocumentListByDir(params);
	if(res.status&&res.data.success){
		return res.data.page;
	}else{
		return [];
	}
  };
  useEffect(() => {
    fetchData(page).then((res) => {
      const results = Array.isArray(res) ? res : [];
      setInitLoading(false);
      setData(results);
      setList(results);
    });
  }, []);

  const onLoadMore = () => {
    setLoading(true);
    setList(data.concat(Array.from({ length: PAGE_SIZE }).map(() => ({ loading: true }))));
    const nextPage = page + 1;
    setPage(nextPage);
    fetchData(nextPage).then((res) => {
      const results = Array.isArray(res) ? res : [];
      const newData = data.concat(results);
      setData(newData);
      setList(newData);
      setLoading(false);
      // Resetting window's offsetTop so as to display react-virtualized demo underfloor.
      // In real scene, you can using public method of react-virtualized:
      // https://stackoverflow.com/questions/46700726/how-to-use-public-method-updateposition-of-react-virtualized
      window.dispatchEvent(new Event('resize'));
    });
  };

  const loadMore =
    !initLoading && !loading ? (
      <div
        style={{
          textAlign: 'center',
          marginTop: 12,
          height: 32,
          lineHeight: '32px',
        }}
      >
        <Button onClick={onLoadMore}>加载更多</Button>
      </div>
    ) : null;
	const downloadFile = async(item:DataType) =>{
		await downloadFileById(item.id,item.fileName)
	}
	const locale = {emptyText: '暂无数据'}
	return (
		<List
		  className="demo-loadmore-list"
		  loading={initLoading}
		  itemLayout="horizontal"
		  loadMore={loadMore}
		  locale={locale}
		  dataSource={list}
		  renderItem={(item) => (
			<List.Item
			  actions={[<a key="list-loadmore-more" onClick={()=>downloadFile(item)}>下载</a>]}
			>
			  <Skeleton avatar title={false} loading={item.loading} active>
				<List.Item.Meta
				  title={<a href="https://ant.design">{item.fileName}</a>}
				  description={item.filePath+'   '+ item.uploadDateTime}
				/>
			  </Skeleton>
			</List.Item>
		  )}
		/>
	);
};

export default forwardRef(DirectoryDocumentList);